/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 //对每一个从根节点到叶子节点做前缀和分析
 //边遍历，边计算
class Solution {
    long long prevSum = 0;
    int num = 0;
    unordered_map<long long, int> hash;

    void dfs(TreeNode* root, int targetSum)
    {
        if (root == nullptr)
            return;

        prevSum += root->val;
        if (hash.count(prevSum - targetSum))
            num += hash[prevSum - targetSum];

        hash[prevSum]++;
        dfs(root->left, targetSum);
        dfs(root->right, targetSum);
        hash[prevSum]--;
        prevSum -= root->val;
    }
public:
    int pathSum(TreeNode* root, int targetSum) {
        hash[0] = 1;
        dfs(root, targetSum);
        return num;
    }
};